package com.example.waibao.service.impl;

import cn.hutool.core.util.IdUtil;
import com.aliyuncs.utils.StringUtils;
import com.example.waibao.entity.Message;
import com.example.waibao.entity.ResponseResult;
import com.example.waibao.service.SseEmitterService;
import com.github.pagehelper.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class SseEmitterServiceImpl implements SseEmitterService {
    /**
     * 容器，保存连接，用于输出返回
     */
    private static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();

    @Override
    public SseEmitter connect(String clientId) {
        // 设置超时时间，0表示不过期。默认30秒，超过时间未完成会抛出异常：AsyncRequestTimeoutException
        SseEmitter sseEmitter = new SseEmitter();
        // 是否需要给客户端推送ID
//        if (StringUtil.isEmpty(clientId)) {
//            clientId = IdUtil.simpleUUID();
//        }
        // 注册回调
     //   sseEmitter.onCompletion(completionCallBack(clientId));
       // sseCache.put(clientId, sseEmitter);

      //  log.info("创建新的sse连接，当前用户：{}", clientId);

        try {
            sseEmitter.send(SseEmitter.event().comment("welcome"));
        } catch (IOException e) {
      //      logger.error("SseEmitterServiceImpl[createSseConnect]: 创建长链接异常，客户端ID:{}", clientId, e);
     //       throw new BusinessException("创建连接异常！", e);
            e.printStackTrace();
        }

        sseEmitter.onCompletion(()->{
            sseCache.remove(clientId);
        });

        sseEmitter.onError((throwable)->{
            sseCache.remove(clientId);
        });
        sseEmitter.onTimeout(()->{
            sseCache.remove(clientId);
        });
        sseCache.put(clientId, sseEmitter);
        return sseEmitter;
    }

    @Override
    public void sendMessage(Message message) {
        message.setTotal(sseCache.size());

        sseCache.forEach((clientId, sseCache)->{
            try {
                sseCache.send(message, MediaType.APPLICATION_JSON);
            }catch (IOException e){
                e.printStackTrace();
            }
        });


    }


}

